<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Config, DB, Auth;
use App\Models\Admin\User;
use App\Models\Admin\DealRecord;
use App\Exports\WithdrawExport;
use Carbon\Carbon;
use Excel;

class Withdraw extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'user_id', 'bank_name', 'bank_code', 'deposit',
        'accepter_name', 'accepter_phone', 'withdraw', 'service_fee', 
        'status', 'apply_at', 'examine_at', 'refuse_at', 'why', 
        'created_at', 'updated_at'
    ];

    //获取提现列表数据  
    public function getData($res){

        $pageSize = $res['pageSize'];
        $storeId = Auth::guard('admin')->user()->store_id;
        $requestStoreId = $res['storeId'];

        $sql = $this->withdrawSearch($res);
        
        if ($storeId == 0) {
            // 管理员查看全部店铺分类列表 按店铺排序
            if ($requestStoreId == 0) {
                $data_sql = $sql->orderBy('store_id')->orderBy('apply_at', 'desc');
            } else {
                $data_sql = $sql->where('store_id', $requestStoreId)->orderBy('apply_at', 'desc');
            }
        } else {
            // 店家只能查看自己店的分类
            $data_sql = $sql->where('store_id', $storeId)->orderBy('apply_at', 'desc');
        }

        if(!empty($res["report"])) {
            $data = $data_sql->get()->toArray();
            $data = $this->handleImportWithdrawData($data);
            return Excel::download(new WithdrawExport($data), 'withdraw.xlsx');
        }

        $data = $data_sql->paginate($pageSize)->toArray();
        $result = $this->withdrawDataList($data);
        return $this->success($result);
    } 

    //提现列表搜索
    public function withdrawSearch($res){
        $where = [];
        
        if(!empty($res["user_id"])){
            $where["user_id"] = $res["user_id"];
        }
        
        $status = array_keys(Config::get("const.withdraw_status_str"));
        if(is_numeric($res["status"])){
            if(in_array($res["status"],$status)){
                $where['status'] = $res["status"]; 
            }
        }
        return $this->where($where);
    }

    //导出数据格式处理
    private function handleImportWithdrawData($data)
    {
        $arr = [];
        $memberIds = array_unique(array_column($data,"user_id"));
        $member = User::whereIn("id",$memberIds)->get()->toArray();
        foreach($data as $k => $v) {
            $item = [];
            $item['apply_at'] = $v['apply_at'];
            $item['user_id'] = $v['user_id'];
            $item['realname'] = "";
            foreach($member as $key => $val){
                if($val["id"] == $v["user_id"]){
                    $item['realname'] = $val["true_name"];
                }
            }
            $item['accepter_name'] = $v['accepter_name'];
            $item['accepter_phone'] = $v['accepter_phone'];
            $item['withdraw'] = $v['withdraw']/100;
            $item['reality_account'] = ($v["withdraw"]-$v["service_fee"]) / 100;
            $item['bank_name'] = $v['bank_name'];
            $item['deposit'] = $v['deposit'];
            $item['bank_code'] = "'".$v['bank_code'];
            $item['state_cn'] = Config::get("const.withdraw_status_str")[$v["status"]];
            $item['examine_at'] = $v['examine_at'];
            array_push($arr, $item);
        }

        return $arr;
    }

    //提现列表数据处理
    public function withdrawDataList($data){
        if(empty($data)){
            return null;
        }
        $memberIds = array_unique(array_column($data["data"],"user_id"));
        $member = User::whereIn("id",$memberIds)->get()->toArray();
        $goldsum = $this->whereIn("user_id",$memberIds)->where("status",1)->groupBy("user_id")->select("user_id",Db::raw("sum(withdraw) as goldsum"))->get()->toArray();
        foreach($data["data"] as $key => $val){
            //实际到账
            $data["data"][$key]["reality_account"]= $val["withdraw"]-$val["service_fee"];//number_format(($val['gold'] * (1-0.006)/100)-1, 2, '.', '');
            //提现金额
            $data["data"][$key]["withdraw"]= $val["withdraw"]/100;
            //状态
            $data["data"][$key]["state_cn"] = Config::get("const.withdraw_status_str")[$val["status"]];
            $data["data"][$key]["surplus_account"] = 0;
            $data["data"][$key]["realname"] = "";
            $data["data"][$key]["goldsum"] = 0;
            foreach($member as $k => $v){
                if($val["user_id"] == $v["id"]){
                    $data["data"][$key]["surplus_account"] = $v["gold"]/100;
                    $data["data"][$key]["realname"] = $v["true_name"];
                }
            }

            foreach($goldsum as $ks => $vs){
                if($val["user_id"] == $vs["user_id"]){
                    $data["data"][$key]["goldsum"] = $vs["goldsum"]/100;
                }  
            }
        }
        return $data;
    }

    //同意提现
    public function agree($id){
        $data = [];
        $data["status"] = 1;   
        $data["examine_at"] = Carbon::now()->toDateTimeString();   
        if(is_array($id)){
            $result = $this->whereIn("id",$id)->where("status",0)->update($data);
        }else{
            $result = $this->where("id",$id)->where("status",0)->update($data);
        }
        return $result;
    }

    //拒绝提现
    public function refuse($id,$why){
        DB::beginTransaction();
		try{
			$res=$this->where("id",$id)->where("status",0)->update(["status"=>2,"why"=>$why,"examine_at"=>Carbon::now()->toDateTimeString()]);
			$info=[];
			$withdraw=$this->where("id",$id)->select("user_id","withdraw")->first();
			$member=User::where("id",$withdraw['user_id'])->first();
			
			$info['user_id']=$withdraw['user_id'];
			$info['store_id']=$member['store_id'];
			$info['amount']=$withdraw['withdraw'];
			$info['reason']="拒绝提现";
			$info['status']=3;
			$info['deal_type']=5;
			$info['order_type']=2;
			$info['last_balance']=$member['gold'];
			$info['new_balance']=$member['gold']+$withdraw['withdraw'];
			$info['deal_item_id']=$id;
			$info['grade']=$member['grade'];
			$info['jm_type']=1;
			$dealrecord=new DealRecord;
			$result=$dealrecord->returnedMoney($info);
            if($result['code'] != 20000){
                return $result;
            }

            DB::commit();
            return $this->success(["info"=>"拒绝提现操作成功"]);

		}catch (\Exception $e) {
	        DB::rollBack();
            return $e;
	        return $this->error(["info"=>"拒绝提现操作失败"]);  
		}  
    }
}